package com.cassi.rabbitmq.turorials.config;

import com.cassi.rabbitmq.turorials.config.meta.RabbitMqMata;
import lombok.Setter;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

/**
 * @author caasi
 * @since 2022-01-24 14:28:12
 */

@ConfigurationProperties(prefix = "cassi.rabbit")
@Configuration
@Setter
public class RabbitMqConfig {
    
    private RabbitMqMata vip;
    
    @Bean("rabbitmq-connection-factory-vip")
    @Primary
    public ConnectionFactory connectionFactoryVip(){
        CachingConnectionFactory factory = new CachingConnectionFactory();
        factory.setHost(vip.getHost());
        factory.setPort(vip.getPort());
        factory.setUsername(vip.getUsername());
        factory.setPassword(vip.getPassword());
        return factory;
    }
    
    @Bean("rabbitmq-template-vip")
    @Primary
    public RabbitTemplate rabbitTemplate(@Qualifier("rabbitmq-connection-factory-vip") ConnectionFactory factory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate();
        rabbitTemplate.setConnectionFactory(factory);
        rabbitTemplate.setMessageConverter(jackson2JsonMessageConverter());
        return rabbitTemplate;
    }
    
    @Bean("amqp-admin-vip")
    @Primary
    public AmqpAdmin amqpAdmin180(@Qualifier("rabbitmq-connection-factory-vip") ConnectionFactory factory){
        RabbitAdmin rabbitAdmin = new RabbitAdmin(factory);
        return rabbitAdmin;
    }

    @Bean(name = "rabbitmq-container-factory-vip")
    public SimpleRabbitListenerContainerFactory hospSyncFactory(
            @Qualifier("rabbitmq-connection-factory-vip") ConnectionFactory connectionFactory
    ) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setAcknowledgeMode(AcknowledgeMode.AUTO);
        factory.setPrefetchCount(10);
        return factory;
    }
    
    @Bean
    public MessageConverter jackson2JsonMessageConverter(){
        return new Jackson2JsonMessageConverter();
    }
    
}
